<template>
	<view style="padding: 40rpx 20rpx">
		<scan></scan>
		<div>
			<button type="primary" size="mini" v-if="bluetoothStatus == '未连接'" class="bluetooth" @tap="showBlueTooth">
				蓝牙秤:
				{{bluetoothStatus}}
			</button>
			<button type="primary" size="mini" v-else class="bluetooth" @tap="closeConnet()">
				蓝牙秤:
				{{bluetoothStatus}}
			</button>
		</div>
		<view class="package">
			<view class="content-package">
				<view class="">
					<tn-input disabled v-model="package_no" :border="border" placeholder="请扫描获取集包号" />
				</view>
			</view>
			<button type="primary" size="mini" class="bluetooth" @tap="package_no = ''">
				重新扫描
			</button>
		</view>

		<view class="weight" style="margin-bottom: 20rpx;">
			<view class="weight-name">
				包裹重量:
			</view>
			<view class="weight-input">
				<input disabled v-model="$store.state.weight" style="font-size: 28rpx;width: 100%;" class="uni-input"
					confirm-type="search" placeholder="包裹重量" />
			</view>
		</view>
		<view class="search-view">
			<view class="search">
				<text @tap="scanCode()" style="font-size: 50rpx;margin-right: 20rpx;" class="tn-icon-scan"></text>
				<input v-model="waybill_no" style="font-size: 28rpx;width: 100%;" class="uni-input"
					confirm-type="search" placeholder="请输入或扫描运单号进行集包" />
			</view>
			<tn-button @tap="pickup" backgroundColor="tn-bg-blue" fontColor="#fff">确 定</tn-button>
		</view>
		<view class="goods_type">
			<view class="list_content">
				<view class="" style="margin-right: 10rpx;">
					产品标识:
				</view>
				<view @tap="changeType(item)" :class="goods_type_id == item.id?'list_item list_active':'list_item'"
					v-for="(item,index) in typeList" :key="index">
					{{item.name}}
				</view>
			</view>

			<view class="list_content">
				<view class="" style="margin-right: 10rpx;">
					快递类型:
				</view>
				<view @tap="changeExpressType(item)" :class="expressType == item.id?'list_item list_active':'list_item'"
					v-for="(item,index) in expressList" :key="index">
					{{item.name}}
				</view>
			</view>
		</view>
		<view class="scan-content">
			<div class="scan-title">
				<span>扫描明细</span>
				<span>本次扫描数量: {{scanList.length}}</span>
			</div>
			<div style="text-align: center;padding: 40rpx 0;color: #999;" v-if="!scanList.length">
				暂无揽收记录
			</div>
			<div class="scan-list">
				<div v-for="(item,index) in scanList" :key="index" class="scan-item">
					<span> {{item.waybill_no}}</span>
					<span> 重量:{{item.weight}}kg</span>
					<span> {{item.goods_name}}</span>
					<span> {{item.express_name}}</span>
				</div>
			</div>
		</view>
		<view class="" style="display: flex;justify-content: center;margin-top: 100rpx;">
			<tn-button style="margin-right: 10rpx;" @tap="back" width="550rpx" height="80rpx"
				backgroundColor="tn-bg-blue" fontColor="tn-color-white">扫描完成</tn-button>
		</view>
		<tn-modal @tap='clickClose' v-model="showClose" title="提示" content="是否断开连接?" :button="button"></tn-modal>

		<view v-show="show" class="cu-dialog" @tap="show = false">
			<view class="dialog-content">
				<view class="cu-bar" style="margin-bottom: 20rpx;">
					<view class="content" style="color: #ecd2ac;">蓝牙设备</view>
					<tn-loading mode="circle" :show="true"></tn-loading>
				</view>
				<scroll-view scroll-y="true" class="v30">
					<view class="cu-list">
						<view @tap.stop="connect(item)" class="cu-item" v-for="(item,index) in list" :key="index">
							<view class="content" v-if="item.name">{{item.name}}<text
									style="color: black;font-weight: 700;margin-left: 20rpx;">{{item.address}}</text>
							</view>
							<view class="content" v-if="item.name ==' '">
								无名称
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<!-- 		<tn-popup v-model="showBluetooth" mode="bottom" :borderRadius="30">
			<view class="cu-dialog" @tap.stop="">
				<view class="cu-bar" style="margin-bottom: 20rpx;">
					<view class="content" style="color: #ecd2ac;">蓝牙设备</view>
				</view>
				<scroll-view class="v30" scroll-y="true">
					<view class="cu-list">
						<view @tap="connect(item)" class="cu-item" v-for="(item,index) in bluetoothList" :key="index">
							<view v-if="item.name">{{item.name}}</view>
							<view v-if="item.name ==' '">
								无名称
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</tn-popup> -->
	</view>
</template>

<script>
	import scan from "@/common/pdaScan.vue"
	const bluetooth = uni.requireNativePlugin('LY-BluetoothWeight');
	export default {
		components: {
			scan
		},
		data() {
			return {
				package_no: "",
				number: 0,
				scanList: [],
				waybill_no: "",
				showPackage: false,
				packageList: [],
				border: false,
				typeList: [],
				goods_type_id: '',
				bluetoothList: [],
				// showBluetooth: false,
				bluetoothStyle: "未连接",
				bluetoothSocket: null,
				device: null,
				canvasInput: null,
				interval: null,
				bluetoothStatus: '未连接',
				list: [],
				show: false,
				showClose: false,
				button: [{
						text: '取消',
						backgroundColor: '#E6E6E6',
						fontColor: '#FFFFFF'
					},
					{
						text: '确定',
						backgroundColor: '#6f3e25',
						fontColor: '#FFFFFF'
					}
				],
				expressList: [{
					name: "标快",
					id: 1
				}, {
					name: "特快",
					id: 2
				}],
				expressType: '',
				goods_name: '',
				express_name: ''
			}
		},
		onLoad() {
			this.getlistType()
			// if (uni.getStorageSync("bluetoothPrint")) {
			// 	this.connect(JSON.parse(uni.getStorageSync("bluetoothPrint")))
			// }
			this.$api.admin({
				apiUrl: '/package/list',
				param: {}
			}).then((res) => {
				this.packageList = res.data.data.data
			}).catch((err) => {})
			this.list = JSON.parse(uni.getStorageSync('blueList'))
			this.$store.commit('setWeight', 0)
			bluetooth.initBluetooth({
				isPrimitive: false
			})
			if (uni.getStorageSync('deviceInfo')) {
				this.connect(JSON.parse(uni.getStorageSync('deviceInfo')))
			}

		},
		onShow: function() {
			var that = this
			uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器  
			uni.$on('scancodedate', function(data) {
				if (!that.package_no) {
					let num = false

					that.packageList.forEach(item => {
						if (item.package_no == data.code) {
							num = true
						}
					})
					if (num) {
						that.package_no = data.code
					} else {
						uni.showToast({
							title: '未查询到该集包号',
							icon: 'error'
						})
					}
				} else {
					that.waybill_no = data.code
					that.pickup()
				}

			})
		},
		onUnload() {
			bluetooth.disconnectBluetooth();
			this.bluetoothStatus = '未连接'
			this.showClose = false
		},
		methods: {
			changeExpressType(item) {
				if (item.id == this.expressType) {
					this.expressType = ''
					this.express_name = ''
				} else {
					this.expressType = item.id
					this.express_name = item.name
				}
			},
			getlistType() {
				this.$api.admin({
					apiUrl: '/goods/listType',
					param: {}
				}).then((res) => {
					this.typeList = res.data.data.list
					this.goods_type_id = res.data.data.list[0].id
					this.goods_name = res.data.data.list[0].name
				}).catch((err) => {})
			},
			showBlueTooth() {
				uni.vibrateShort()
				bluetooth.initBluetooth({
					isPrimitive: false
				})
				bluetooth.discoveryBluetooth((res) => { //多次回调，可添加到数组展示蓝牙列表
					console.log(res)
					//res数据：{"status":5,"data":{"name":"蓝牙名称","address":"蓝牙地址"}}
					if (res.status == 5 && res.data.name) {
						this.list = this.list.concat(res.data)
						uni.setStorageSync('blueList', JSON.stringify(this.list));
					}
				});
				this.show = true
			},
			// 连接设备
			async connect(item) {
				let self = this;
				uni.vibrateShort()
				bluetooth.connectBlutoothWithName({
					blutoothName: item.name //蓝牙名称
				}, (res) => {
					switch (parseInt(res.status)) {
						case 0: {
							uni.showToast({
								title: '请先配对电子秤',
								icon: 'error'
							})
						}
						break;
						case 1: {
							self.$store.commit('setWeight', res.data)
							// this.weight = res.data;
						}
						break;
						case 2: {
							uni.showToast({
								title: '连接成功',
								icon: 'success'
							})
							uni.setStorageSync('deviceInfo', JSON.stringify(item));
							self.bluetoothStatus = item.name + ' ' + item.address
							self.show = false
						}
						break;
						case 3: {
							// uni.showToast({
							// 	title: '蓝牙已断开',
							// 	icon: 'error'
							// })
							self.bluetoothStatus = '未连接'
						}
						break;
						default:
							break;
					}
				})
			},
			//断开连接
			closeConnet() {
				uni.vibrateShort()
				this.showClose = true
			},
			clickClose(e) {
				uni.vibrateShort()
				if (e.index == 0) {
					this.showClose = false
				} else {
					// this.$store.commit('closeBluetoothAdapter')
					// this.$store.commit('openBluetoothAdapter')
					bluetooth.disconnectBluetooth();
					this.bluetoothStatus = '未连接'
					this.showClose = false
				}
			},

			closeBluetooth() {
				if (!this.bluetoothSocket) return true
				this.bluetoothSocket.close();
				this.bluetoothSocket = null
			},
			closeBlue() {
				uni.setStorageSync("bluetoothPrint", "")
				this.bluetoothStyle = "未连接"
				if (!this.bluetoothSocket) return true
				this.bluetoothSocket.close();
				this.bluetoothSocket = null
			},
			//1.  页面初始化，获取位置，打开蓝牙连接（必须打开定位）
			getBluetooth() {
				this.showBluetooth = true
				let system = uni.getSystemInfoSync(); // 获取系统信息
				if (system.platform === 'android') { // 判断平台
					var that = this
					var context = plus.android.importClass("android.content.Context");
					var locationManager = plus.android.importClass("android.location.LocationManager");
					var main = plus.android.runtimeMainActivity();
					var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
					// 定位检测
					if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
						uni.showModal({
							title: '提示',
							content: '请打开定位服务功能',
							showCancel: false, // 不显示取消按钮
							success() {
								if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
									var Intent = plus.android.importClass('android.content.Intent');
									var Settings = plus.android.importClass('android.provider.Settings');
									var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
									main.startActivity(intent); // 打开系统设置GPS服务页面
								} else {
									console.log('GPS功能已开启');
								}
							}
						});
						return false
					} else {
						console.log('GPS功能已开启');
						that.searchDevices()
						return true
					}
				}
			},
			//2. 搜索蓝牙
			searchDevices() {

				var deviceList = [];
				var main = plus.android.runtimeMainActivity();
				var Context = plus.android.importClass("android.content.Context");
				var BManager = main.getSystemService(Context.BLUETOOTH_SERVICE);
				plus.android.importClass(BManager);
				var BAdapter = BManager.getAdapter();
				plus.android.importClass(BAdapter);
				var lists = BAdapter.getBondedDevices();
				plus.android.importClass(lists);
				var iterator = lists.iterator();
				plus.android.importClass(iterator);
				while (iterator.hasNext()) {
					var d = iterator.next();
					plus.android.importClass(d);
					var temp = {
						name: d.getName(),
						address: d.getAddress(),
						status: d.getBondState(),
						uuids: d.getUuids(),
						op: d
					};
					deviceList.push(temp);
				}
				console.log(deviceList)
				this.bluetoothList = deviceList
				// return deviceList;

			},
			//链接打印机
			// connect: function(item) {
			// 	if (this.bluetoothSocket) {
			// 		this.bluetoothSocket.close();
			// 	}
			// 	this.main = plus.android.runtimeMainActivity();
			// 	var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
			// 	var UUID = plus.android.importClass("java.util.UUID");
			// 	var uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
			// 	var BAdapter = BluetoothAdapter.getDefaultAdapter();
			// 	this.device = BAdapter.getRemoteDevice(item.address);
			// 	plus.android.importClass(this.device);
			// 	this.bluetoothSocket = this.device.createInsecureRfcommSocketToServiceRecord(uuid);
			// 	plus.android.importClass(this.bluetoothSocket);
			// 	if (!this.bluetoothSocket.isConnected()) {
			// 		uni.showLoading({
			// 			title: '检测到设备未连接，尝试连接....'
			// 		})
			// 		this.bluetoothSocket.connect();
			// 	}
			// 	uni.hideLoading()
			// 	uni.setStorageSync("bluetoothPrint", JSON.stringify(item))
			// 	this.bluetoothStyle = item.name
			// 	this.showBluetooth = false
			// 	console.log('设备已连接')
			// },
			async print() {
				if (!this.package_no) {
					this.$t.message.toast('请选择集包号')
					return
				}
				if (!this.bluetoothSocket) {
					this.$t.message.toast('请先连接打印机')
					return
				}
				var that = this
				var outputStream = this.bluetoothSocket.getOutputStream();
				plus.android.importClass(outputStream);
				var string = "! 120 200 200 300 1\r\n" +
					"LABEL\r\n" +
					"PW 575\r\n" +
					"TONE 0\r\n" +
					"SPEED 2\r\n" +
					"ON-FEED IGNORE\r\n" +
					"NO-PACE\r\n" +
					"SETMAG 3 3\r\n" +
					"TEXT 8 0 20 5 拆\r\n" +
					"SETMAG 0 0\r\n" +
					"CENTER\r\n" +
					"BARCODE-TEXT 7 0 5\r\n" +
					"CENTER\r\n" +
					"BARCODE 128 2 1 100 0 100 " + that.package_no + "\r\n" +
					"BARCODE-TEXT OFF\r\n" +
					"FORM\r\n" +
					"PRINT\r\n"
				var bytes = plus.android.invoke(string, 'getBytes', 'gbk');
				outputStream.write(bytes);
				outputStream.flush();
				// bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误  


			},
			confirm(e) {
				this.package_no = e[0].value
			},
			scanCode() {
				var that = this
				// 允许从相机和相册扫码
				uni.scanCode({
					success: function(res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						that.waybill_no = res.result
						that.pickup()
					}
				});
			},
			changeType(item) {
				this.goods_type_id = item.id
				this.goods_name = item.name
			},
			cheackWeight() {
				var that = this
				return new Promise((resove, reject) => {
					var weight1 = ''
					var weight2 = ''
					weight1 = this.$store.state.weight
					var times = setTimeout(() => {
						weight2 = that.$store.state.weight
						if (weight1 == weight2) {
							clearTimeout(times);
							resove(true)
						} else {
							clearTimeout(times);
							resove(false)
						}
					}, 500)
				})
			},
			async pickup() {
				let isWeight = await this.cheackWeight()
				if (!isWeight) {
					uni.showLoading({
						title: '重量未稳定请重试',
						icon: 'none',
						duration: 2000
					});
					return
				}
				uni.showLoading({
					title: '获取扫描信息中...',
					icon: 'none'
				});
				let weightS = this.$store.state.weight
				this.$api.admin({
					apiUrl: '/package/createOrder',
					param: {
						"waybill_no": this.waybill_no,
						"package_no": this.package_no,
						"weight_send": weightS,
						"goods_type_id": this.goods_type_id, //货物类型 ID
						"express_type": this.expressType
					}
				}).then((res) => {
					uni.hideLoading();
					this.scanList.unshift({
						waybill_no: this.waybill_no,
						weight: weightS,
						goods_name: this.goods_name,
						express_name: this.express_name
					})
				}).catch((err) => {
					uni.hideLoading();
				})
			},
			back() {
				uni.reLaunch({
					url: '/pages/index/home'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.content-package {
		border: 1rpx solid #d9d9d9;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
		padding: 0 20rpx;
		width: 500rpx;
	}

	.search-view {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.search {
		border: 1rpx solid #d9d9d9;
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
		width: 80%;
		display: flex;
		align-items: center;
	}

	.weight {
		border-radius: 10rpx;
		display: flex;
		margin-top: 20rpx;

		.weight-name {
			border: 1rpx solid #c7c7c7;
			padding: 10rpx;
			width: 25%;
			text-align: center;
		}

		.weight-input {
			border: 1rpx solid #dcdcdc;
			background-color: #dcdcdc;
			padding: 10rpx;
			width: 75%;
		}
	}

	.scan-content {
		margin-top: 20rpx;

		.scan-title {
			background-color: #3D7EFF;
			padding: 20rpx;
			color: #fff;
			display: flex;
			justify-content: space-between;
		}

		.scan-list {
			margin-top: 30rpx;

			.scan-item {
				border-bottom: 1rpx solid #e7e7e7;
				padding: 30rpx 0;
				display: flex;
				justify-content: space-between;
			}
		}
	}

	.search-view {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.search {
		border: 1rpx solid #d9d9d9;
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
		width: 80%;
		display: flex;
		align-items: center;
	}

	.main {
		border: 1rpx solid #d9d9d9;
		border-radius: 10rpx;
		padding: 40rpx;
		margin-top: 40rpx;
		font-size: 30rpx;

		.content {
			display: flex;
			align-items: center;
			margin-bottom: 30rpx;

			.name {
				margin-right: 10rpx;
				width: 25%;
				text-align: right;
			}
		}
	}

	.bluetooth {
		font-size: 28rpx;
		margin-bottom: 20rpx;
	}


	.cu-bar {
		font-size: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.content {
			margin-right: 10rpx;
			position: relative;
			top: -3rpx;
		}
	}

	.v30 {
		height: 50vh;

		.cu-list {
			.cu-item {
				text-align: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #ecd2ac;
				color: #666;
			}
		}

	}

	.cu-dialog {
		position: fixed;
		background-color: rgba(0, 0, 0, .3);
		width: 100%;
		height: 100vh;
		top: 0;
		left: 0;

		.dialog-content {
			background-color: #fff;
			position: absolute;
			bottom: 0;
			width: 100%;
			padding: 20rpx;
		}
	}

	.list_content {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
		align-items: center;

		.list_item {
			margin-right: 10rpx;
			font-size: 28rpx;
			border: 1rpx solid #d9d9d9;
			margin-bottom: 10rpx;
			padding: 2rpx 10rpx;
			border-radius: 10rpx;
			color: #666;
		}

		.list_active {
			background-color: #3D7EFF;
			border: 1rpx solid #3D7EFF;
			color: #fff;
		}
	}

	.package {
		display: flex;
		align-items: center;
	}
</style>